<?php
/**
 * UserModel.class.php
 * 用户模型
 * 
 * @author  王中艺 <wangzy_smile@qq.com>
 * @date    2017-08-25
 */

namespace Common\Model;

class UserModel extends BaseModel {

    protected $trueTableName    = 't_user';
    protected $cache    = false;

    const ROLE_MAP  = [
        101 => '健康合伙人', 
        102 => '健康教练A', 
        103 => '健康教练B', 
        104 => '健康教练C', 
        105 => '健康推广大使', 
        106 => '健康家长'
    ];
    const SEX_MAP   = [
        1   => '男',
        2   => '女'
    ];
    
    /**
     * 设置查询条件
     * @param   $condition
     * @param   $tbName
     * @return  $where
     */
    function setCondition($condition, $tbName = ''){
        $where  = parent::setCondition($condition, $tbName);
        $tbName     = $tbName ? $tbName.'.' : '';

        //关键词查询
        if(isset($condition['keyword']) && $condition['keyword'] != ''){
            $where[$tbName.'nickname|'.$tbName.'truename|'.$tbName.'username'] = ['like', '%'.$condition['keyword'].'%'];
        }

        //VIP查询
        if(isset($condition['is_vip']) && $condition['is_vip'] == true){
            $where[$tbName.'vip_level'] = ['egt', 1];
            $where[$tbName.'vip_endtime']   = ['egt', time()];
        }
        
        //时间查询
        if(isset($condition['date_start']) && $condition['date_start'] != ''){
            $where[$tbName.'subscribe_time'][]    = ['egt', strtotime($condition['date_start'])];
        }
        if(isset($condition['date_end']) && $condition['date_end'] != ''){
            $where[$tbName.'subscribe_time'][]    = ['lt', strtotime($condition['date_end'])];
        }

        //默认状态查询
        if(!isset($condition['status']) || !is_numeric($condition['status'])){
            $where[$tbName.'status']    = ['neq', -1];
        }
        if(isset($condition['status']) && $condition['status'] === false){
            unset($where[$tbName.'status']);
        }

        return $where;
    }

    /**
     * 字段解析
     * @param   $data
     * @param   $batch
     * @return  $data
     */
    static function resolveColumn($data, $batch = false){
        $resolveColumn   = function(&$item){
            $item['subscribe_date'] = date('Y-m-d', $item['subscribe_time']);
            $item['role_text']  = C('USER_ROLE.'.$item['role_id']);
            if($item['vip_endtime'])
                $item['vip_enddate']    = date('Y-m-d', $item['vip_endtime']);
            if($item['child_birthday'])
                $item['child_birthday_date']    = date('Y-m-d', $item['child_birthday']);
        };

        if($batch){
            foreach($data as &$item){
                $resolveColumn($item);
            }
        }else{
            $resolveColumn($data);
        }

        return $data;
    }

    /**
     * 获取用户信息
     * @param   $condition
     * @return  $userInfo
     */
    function getItem($condition){
        $where  = $this->setCondition($condition);
        $userInfo   = $this->where($where)->cache($this->cache)->find();
        return $userInfo;
    }

    /**
     * 获取用户详情信息
     * @param   $id
     * @return  $info
     */
    function getDetailItem($id){
        //To do...
    }

    /**
     * 获取下级用户列表
     * @param   $userId
     * @param   $condition
     * @param   $sortInfo
     * @param   $page
     * @param   &$pageHtml
     * @param   &$count
     * @return  $list
     */
    function getChildList($userId, $condition, $sortInfo, $page, &$pageHtml, &$count){
        $where  = $this->setCondition($condition, 'a');
        $userInfo   = $this->getItem(['id' => $userId]);
        if($userInfo['role_id'] == 101){
            $where['b.dean_id'] = $userId;
        }else if($userInfo['role_id'] >= 102 && $userInfo['role_id'] <= 104){
            $where['b.expand_id']   = $userId;
        }else if($userInfo['role_id'] == 105){
            $where['b.teacher_id']  = $userId;
        }else{
            $where['b.parent_id']   = $userId;
        }

        $query  = $this->table('t_user a')
            ->join('right join t_user_relative b on a.id = b.user_id')
            ->where($where)
            ->cache($this->cache);

        if($pageHtml === true){
            $Page   = new \Think\Page((clone $query)->count(), C('PAGE_COUNT'));
            $pageHtml   = $Page->angularShow();
        }

        if($count === true){
            $count  = (clone $query)->count();
        }

        if($sortInfo){
            $sort   = $sortInfo['desc'] ? $sortInfo['field'].' desc' : $sortInfo['field'];
        }
        
        $list   = $query->page($page, C('PAGE_COUNT'))->field('a.*')->select();
        $list   = self::resolveColumn($list, true);
        return $list;
    }

    /**
     * 追加下级用户数量
     * @param   $info
     * @param   $batch
     * @return  $info 
     */
    function appendChildUserCount($info, $batch = false){
        if($batch){
            //批量追加下级用户
            foreach($info as $item){
                //下线人数计算
                if($item['role_id'] == 101){
                    $deanIds[]  = $item['id'];
                }else if(in_array($item['role_id'], [102, 103, 104])){
                    $expandIds[]    = $item['id'];
                }else if($item['role_id'] == 105){
                    $teacherIds[]   = $item['id'];
                }else{
                    $parentIds[]    = $item['id'];
                }
            }

            //分角色计算下计用户数量
            if(isset($deanIds)){
                $deanChildCountInfo     = M('t_user_relative', null)
                    ->where('dean_id in (%s)', implode(',', $deanIds))
                    ->group('dean_id')
                    ->getField('dean_id as user_id, count(user_id) as count');
            }
            if(isset($expandIds)){
                $expandChildCountInfo   = M('t_user_relative', null)
                    ->where('expand_id in (%s)', implode(',', $expandIds))
                    ->group('expand_id')
                    ->getField('expand_id as user_id, count(user_id) as count');
            }
            if(isset($teacherIds)){
                $teacherChildCountInfo  = M('t_user_relative', null)
                    ->where('teacher_id in (%s)', implode(',', $teacherIds))
                    ->group('teacher_id')
                    ->getField('teacher_id as user_id, count(user_id) as count');
            }
            if(isset($parentIds)){
                $parentChildCountInfo   = M('t_user_relative', null)
                    ->where('parent_id in (%s)', implode(',', $parentIds))
                    ->group('parent_id')
                    ->getField('parent_id as user_id, count(user_id) as count');
            }

            //整合下级用户角色数量信息
            $childCountInfo     = (array)$deanChildCountInfo +
                (array)$expandChildCountInfo +
                (array)$teacherChildCountInfo +
                (array)$parentChildCountInfo;

            foreach($info as &$item){
                $item['child_count']    = $childCountInfo[$item['id']] ? 
                    $childCountInfo[$item['id']] : 0;
            }
        }

        return $info;
    }
}